import 'package:auto_size_text/auto_size_text.dart';
import 'package:disable_battery_optimization/disable_battery_optimization.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/utils.dart';

class RuntimeSettings extends StatefulWidget {
  const RuntimeSettings({super.key});

  @override
  State<RuntimeSettings> createState() => _RuntimeSettingsState();
}

class _RuntimeSettingsState extends State<RuntimeSettings> {

  bool _isBatteryOptimizationDisabled = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      _getBatteryOptimize();
    });

  }

  void _getBatteryOptimize(){
    DisableBatteryOptimization.isBatteryOptimizationDisabled.then((res){
      _isBatteryOptimizationDisabled = res??false;
      setState(() {});
    });

  }

  void _requestNotBatteryOptimize() async{
    if(!_isBatteryOptimizationDisabled){
      await DisableBatteryOptimization.showDisableBatteryOptimizationSettings();
      _getBatteryOptimize();
    }

  }

  void _toAutoStart(){
    DisableBatteryOptimization.toAutoStart();
  }

  void _toBatteryOptimize(){
    if(!_isBatteryOptimizationDisabled){
      Get.snackbar('hint'.tr, 'grand_battery_optimize_permission_first'.tr);
    }else{
      DisableBatteryOptimization.toBatteryOptimize();
    }

  }

  @override
  Widget build(BuildContext context) {
    return _buildRunTimeSetting();
  }

  Widget _buildRunTimeSetting() => Column(
    children: [
      _buildListTile(name: 'battery_optimize_permission',
          onPressed: _requestNotBatteryOptimize,
        buttonName: _isBatteryOptimizationDisabled ? 'granted' : null
      ),
      _buildListTile(name: 'auto_start', onPressed: _toAutoStart),
      _buildListTile(
          name: 'battery_optimize',
          onPressed: _toBatteryOptimize
      ),
    ],
  );

  Widget _buildListTile({
    required String name,
    String? buttonName,
    Function()? onPressed
  }) => Builder(builder: (ctx){
    return ListTile(
      title: Text(name.tr, style: TextStyle(
          color: DefaultTextStyle.of(ctx).style.color
      ),),
      subtitle: Text('${name}_desc'.tr, style: TextStyle(
        color: DefaultTextStyle.of(ctx).style.color,
          fontSize: 12
      ),),
      trailing: SizedBox(
        width: MediaQuery.sizeOf(ctx).width * 0.3,
        child: ElevatedButton(
          onPressed: onPressed,
          child: AutoSizeText((buttonName??'${name}_button').tr, maxLines: 1, minFontSize: 10, overflow: TextOverflow.ellipsis,),
        ),
      ),
    );
  });
}
